package com.woniuxy.joylifeshop.service.serviceImpl;

import com.woniuxy.common.entity.ShopChat;
import com.woniuxy.common.entity.ShopChatExample;
import com.woniuxy.common.mapper.ShopChatMapper;
import com.woniuxy.joylifeshop.exception.ShopChatException;
import com.woniuxy.joylifeshop.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    ShopChatMapper shopChatMapper;

    /**
    * @Author SooYoo
    * @Description
    * @Param
    * @Return
    **/
    @Override
    public List<ShopChat> readChatContentByUserIdAndMerchantId(String userId, String merchantId) {

        try {
            ShopChatExample shopChatExample = new ShopChatExample();
            ShopChatExample.Criteria criteria = shopChatExample.createCriteria();
            criteria.andMerchantIdEqualTo(merchantId);
            criteria.andUserIdEqualTo(userId);
            shopChatExample.setOrderByClause("date ASC");

            List<ShopChat> shopChats = shopChatMapper.selectByExample(shopChatExample);

            for(ShopChat shopChat:shopChats){
                System.out.println(shopChat.getDate());
            }

            return shopChats;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShopChatException();
        }

    }

    /**
    * @Author SooYoo
    * @Description
    * @Param
    * @Return
    **/
    @Override
    public void addessay(String userId, String merchantId, String essay,String listId) {

        try {
            ShopChat shopChat = new ShopChat();
            shopChat.setMsgId(UUID.randomUUID().toString());
            shopChat.setDate(new Date());
            shopChat.setMerchantId(merchantId);
            shopChat.setContent(essay);
            shopChat.setUserId(userId);
            shopChat.setListId(listId);

            shopChatMapper.insert(shopChat);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShopChatException();
        }

    }

    /**
    * @Author SooYoo
    * @Description 最新的一条聊天记录
    * @Param
    * @Return
    **/
    @Override
    public ShopChat recentOneChatObject(String merchatId, String userId) {

        ShopChatExample shopChatExample = new ShopChatExample();
        ShopChatExample.Criteria criteria = shopChatExample.createCriteria();
        criteria.andMerchantIdEqualTo(merchatId);
        criteria.andUserIdEqualTo(userId);
        shopChatExample.setOrderByClause("date DESC");

        List<ShopChat> shopChats = shopChatMapper.selectByExample(shopChatExample);

        if (!shopChats.isEmpty()){
            ShopChat shopChat = shopChats.get(0);
            return shopChat;
        }

        ShopChat shopChat = new ShopChat();
        shopChat.setContent("暂时没有新会话");

        return shopChat;
    }
}
